package com.beaven.imclient.data;

import com.beaven.model.data.group.GroupPresenter;
import com.beaven.model.data.user.CategoryPresenter;
import com.beaven.model.data.user.ContactPresenter;
import com.beaven.model.model.db.Category;
import com.beaven.model.model.db.Group;
import com.beaven.model.model.db.User;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import rx.Observable;
import rx.Subscriber;
import timber.log.Timber;

/**
 * author: Beaven
 * time: 2017/5/27 17:07
 *
 * 好友列表和群组列表数据源管理
 */

public abstract class FriendRepository
    implements CategoryPresenter.OnCategoryLoad, ContactPresenter.OnContractLoad,
    GroupPresenter.OnGroupLoad {

  private CategoryPresenter categoryPresenter;
  private ContactPresenter contactPresenter;
  private GroupPresenter groupPresenter;

  private List<ItemCategory> itemCategoryList;

  private ItemTitle userTitle;
  private ItemTitle groupTitle;

  private OnList onList;

  protected Observable<List<MultiItemEntity>> sub;
  private boolean isFirst = true;

  protected FriendRepository() {
    categoryPresenter = new CategoryPresenter(this);
    contactPresenter = new ContactPresenter(this);
    groupPresenter = new GroupPresenter(this);

    sub = Observable.create(new Observable.OnSubscribe<List<MultiItemEntity>>() {
      @Override public void call(final Subscriber<? super List<MultiItemEntity>> subscriber) {
        onList = new OnList() {
          @Override public void listMulti(List<MultiItemEntity> entities) {
            subscriber.onNext(entities);
          }
        };
      }
    });
  }

  // 数据库监听，加载
  protected void load() {
    categoryPresenter.loadData();
    contactPresenter.loadData();
    groupPresenter.loadData();
  }

  // 取消加载，监听
  protected void destroy() {
    contactPresenter.destroy();
    categoryPresenter.destroy();
    groupPresenter.destroy();
  }

  // 好友列表
  @Override public void loadContract(List<User> users) {
    userTitle = new ItemTitle("联系人");
    for (ItemCategory cate : itemCategoryList) {
      int online = 0;
      int sum = 0;
      List<ItemUser> userList = new LinkedList<>();
      for (User user : users) {
        if (cate.getId().equals(user.getCategoryId())) {
          ItemUser itemUser = ItemUser.build(user);
          userList.add(itemUser);
          sum += 1;
          if (user.isOnline()) {
            online += 1;
          }
        }
      }
      String status = String.format(Locale.CHINESE, "%d/%d", online, sum);
      cate.setStatus(status);
      cate.setSubItems(userList);
      userTitle.addSubItem(cate);
    }
    groupPresenter.loadLocal();
  }

  // 分组列表
  @Override public void loadCategory(List<Category> categories) {
    itemCategoryList = new LinkedList<>();
    for (Category cate : categories) {
      itemCategoryList.add(ItemCategory.build(cate));
    }
    contactPresenter.loadLocal();
  }

  // 群组列表
  @Override public void loadGroup(List<Group> groups) {
    groupTitle = new ItemTitle("群组");
    for (Group group : groups) {
      groupTitle.addSubItem(ItemCategory.build(group));
    }
    build();
  }

  @Override public void notifyContract() {
    categoryPresenter.loadLocal();
    Timber.i("联系人列表更新");
  }

  @Override public void notifyCate() {
    categoryPresenter.loadLocal();
    Timber.i("分组列表更新");
  }

  @Override public void notifyGroup() {
    categoryPresenter.loadLocal();
    Timber.i("群组列表更新");
  }

  // 数据组合
  private void build() {
    List<MultiItemEntity> multiItemEntityList = new ArrayList<>();
    multiItemEntityList.add(userTitle);
    if (userTitle.hasSubItem()) {
      List<ItemCategory> categoryList = userTitle.getSubItems();
      for (int i = 0; i < categoryList.size(); i++) {
        ItemCategory category = categoryList.get(i);
        multiItemEntityList.add(category);
        // 判断当前分组列表是否打开，是否加载分组中好友
        if (category.isExpand()) {
          multiItemEntityList.addAll(category.getSubItems());
        }
      }
    }
    multiItemEntityList.add(groupTitle);
    if (groupTitle.hasSubItem()) {
      multiItemEntityList.addAll(groupTitle.getSubItems());
    }
    // 第一次直接加载数据库数据显示列表，提高显示效率
    if (isFirst) {
      showList(multiItemEntityList);
      isFirst = false;
    } else {
      onList.listMulti(multiItemEntityList);
    }
  }

  protected abstract void showList(List<MultiItemEntity> entities);

  interface OnList {
    void listMulti(List<MultiItemEntity> entities);
  }
}
